package main.ejbs;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import main.entities.Patient;
import main.interfaces.PatientBusinessLocal;

@Stateless(name = "PatientBusiness", mappedName="ejb/PatientBusiness")
public class PatientBusiness implements PatientBusinessLocal, Serializable {
	
	/**
	 * GUID for Serializable.
	 */
	private static final long serialVersionUID = 4733065009000036411L;
	
	@PersistenceContext(name = "PatientFirstXaDsrc")
	private EntityManager _em;
	
	@Override
	public Patient getPatient(Integer id) {
		return _em.find(Patient.class, id);
	}
	
	@Override
	public List<Patient> getAllPatients() {
		List<Patient> resultSet = new LinkedList<Patient>();
		String queryString = "SELECT p FROM Patient p";
		TypedQuery<Patient> query = _em.createQuery(queryString, Patient.class);
		
		try {
			resultSet = query.getResultList();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		
		return resultSet;
	}

	@Override
	public Patient savePatient(Patient patient) {
		return _em.merge(patient);
	}

	@Override
	public void addPatient(Patient patient) {
		patient.setId(null);
		_em.persist(patient);
	}

	@Override
	public boolean deletePatient(Patient patient) {
		try {
			patient = _em.find(Patient.class, patient.getId());
			_em.remove(patient);
			return true;
		}
		catch(Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
